<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\admin\model\GoodsType;
use app\admin\model\Goods as good;
use app\admin\model\GoodsAttr;
use Db;


class Goods extends Controller
{   
    protected $middleware = [
        'Before'=> ['only' 	=> ['index'] ],
    ];
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //展示产品列表
        $list =  good::paginate(5);
        // echo '<pre>';
        // var_dump($data);
        // die;
        return view('',['list'=>$list]);
    }
    //添加商品
    public function add_goods()
    {   
        //取出顶级分类
        $model = new GoodsType;
        $data['data'] = $model->topCat();
        // echo '<pre>';
        // var_dump($data);die;
        // $this->assign('data',$data);
        return view('picture-add',$data);
    }
    //取出所有商品分类供树形结构使用
    public function getGoodsType()
    {
        $model = new GoodsType;
        $data = $model->getGoodsType();

        $data = json_encode($data);
        // echo '<pre>';
        // var_dump($data);die;
        return $data;
    }

    //根据相应的1级分类id取出对应的商品
    public function type1()
    {
        $model = new good;
        $value = $_POST['type_id'];
        $data = $model->getAll1($value);
        return $data;
    }
    //根据二级分类id 取出数据
    public function type2()
    {
        $model = new good;
        $value = $_POST['type_id'];
        $data = $model->getAll2($value);
        return $data;
    }
    //根据三级分类id取出数据
    public function type3()
    {
        $model = new good;
        $value = $_POST['type_id'];
        $data = $model->getAll3($value);
        return $data;
    }
    //根据父id取出对应的子类
    public function ajax_get_type()
    {
        $id = (int)$_GET['id'];
        //根据这个ID查询子类
        $model = new GoodsType;
        $data = $model->getCat($id);

        echo json_encode($data);
    }
    //接收发布商品中富文本编辑器中的图片资源
    public function images()
    {   
        $file = request()->file('file');

        $url = env('root_path');
        $info = $file->move( $url.'public/static/uploads/admin/fuwenben/');

        if($info){
            return json([
                'code'=>0,
                'msg'=>'图片上传成功',
                'data'=> [
                    'src'=>'/static/uploads/admin/fuwenben/'.$info->getSaveName(),
                ]
            ]);
        }else{
            return json([
                'code'=>1,
                'msg'=>'图片上传失败',
            ]);
        }
    }
    
    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {   
        $model = new GoodsType;
        $data['type'] = $model->topCat();

        return view('create',$data);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    //主图上传接口
    public function upload()
    {   
        $files = request()->file('file');


        foreach($files as $file){
            // 循环多张图片 依次生成缩略图以及把地址插入数据表 goods_image
            $url = env('root_path');
            $info = $file->move( $url.'public/static/uploads/admin/');
            if($info){
               $image = \think\Image::open($url.'public/static/uploads/admin/'.$info->getSaveName());
                // var_dump($image);
               $image->thumb(150, 150)->save($url.'public/static/uploads/admin/small/'.$info->getFilename());
               $image->thumb(400, 400)->save($url.'public/static/uploads/admin/mind/'.$info->getFilename());
               $image->thumb(800, 800)->save($url.'public/static/uploads/admin/big/'.$info->getFilename());
               $small_path = '/static/uploads/admin/small/'.$info->getFilename();
               $mind_path = '/static/uploads/admin/mind/'.$info->getFilename();
               $big_path = '/static/uploads/admin/big/'.$info->getFilename();
               $data = ['goods_id'=> $spuId,'small'=>$small_path,'mind'=>$mind_path,'big'=>$big_path];
               Db::table('goods_image')->strict(false)->insert($data);

               return json([
                'code'=>0,
                'msg'=>'图片上传成功',
                ]);

            }else{
                return json([
                'code'=>1,
                'msg'=>'图片上传失败',
                ]);
            }    
        }


       
    }

    public function save(Request $req)
    {     
        // echo '<pre>';
        // var_dump($req->attr);

        $spuId = time().rand(1000,9999);
        $imgs = request()->file('img');

        $url = env('root_path');
        $info = $imgs->move( $url.'public/static/uploads/admin/goodsfm/');
        $img = '/static/uploads/admin/goodsfm/'.$info->getSaveName();

        // echo '<pre>';
        // var_dump($files );die;
        $model = new GoodsAttr;

        $model->goods_id = $spuId;

        for($i=0;$i<count($_POST['attr_key']);$i++){

            $model = new GoodsAttr;
            $model->goods_id = $spuId;
            $model->attr_name = $_POST['attr_key'][$i];
            $model->attr_value = $_POST['attr_value'][$i];
            
            $model->save();
        }
        
        $files = request()->file('image');

        foreach($files as $file){
            // 循环多张图片 依次生成缩略图以及把地址插入数据表 goods_image
            $url = env('root_path');
            $info = $file->move( $url.'public/static/uploads/admin/');
            if($info){
               $image = \think\Image::open($url.'public/static/uploads/admin/'.$info->getSaveName());
                // var_dump($image);
               $image->thumb(800, 800)->save($url.'public/static/uploads/admin/big/'.$info->getFilename());
               $big_path = '/static/uploads/admin/big/'.$info->getFilename();
               $image->thumb(400, 400)->save($url.'public/static/uploads/admin/mind/'.$info->getFilename());
               $mind_path = '/static/uploads/admin/mind/'.$info->getFilename();
               $image->thumb(230, 230)->save($url.'public/static/uploads/admin/small/'.$info->getFilename());
               $small_path = '/static/uploads/admin/small/'.$info->getFilename();
               $data = ['goods_id'=> $spuId,'small'=>$small_path,'mind'=>$mind_path,'big'=>$big_path];
               Db::table('goods_image')->strict(false)->insert($data);
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }    
        }
        // echo '<pre>';
        // die;
        // $_POST['goods_id'] = time().rand(1000,9999);

        //将一维数组中的每二个组合 转换成二位数组
        $district = isset($_POST['attr'])?$_POST['attr']:false;
        if($district == false){
            return $this->error('sku不能为空');
        }
        $count = count($district);
        $arr = array();
        for($y = 0; $y < $count/2; $y++){
            for($x = 0; $x < 2; $x++){
                $arr[$y][$x] = $district[$y*2+$x];
            }
        }

        $str = [];
        foreach($arr as $v){
            $str[] = implode(';',$v);
        }

        $_POST['attr'] = $str;

        // var_dump($_POST['attr']);

        // 把商品的非关键属性输入商品表goods  
        $data = ['images'=>$img,'spu_price'=>$_POST['spu_price'],'goods_name'=>$_POST['goods_name'],'description'=>$_POST['content'],'type1_id'=>$_POST['type1_id'],'type2_id'=>$_POST['type2_id'],'type3_id'=>$_POST['type3_id'],'brand_id'=>1,'spu_volume'=>0,'spu_id'=> $spuId];
        Db::table('goods')->strict(false)->insert($data);

        // 按照颜色以及尺码生成的sku插入goods_sku表
        for($i=0;$i<count($_POST['attr']);$i++){
            $data = ['goods_id'=>$spuId ,'sku_attr'=>$_POST['attr'][$i],'sku_price'=>$_POST['price'][$i],'sku_num'=>$_POST['count'][$i],'sku_volnme'=>0];
            // Db::table('goods_sku')->strict(false)->insert($data);
            $skuId = Db::name('goods_sku')->insertGetId($data);
         
                $arr1 = [];
                $arr1 = explode(';',$_POST['attr'][$i]);

                var_dump($arr1);

                for($j=0;$j<count($arr1);$j++){
                    $arr2 = [];
                    $arr2 = explode(':',$arr1[$j]);

                    $data = ['sku_key_id'=>$arr2[0],'sku_value_id'=>$arr2[1],'sku_id'=>$skuId];
                    Db::table('goods_sku_attr')->strict(false)->insert($data);
                    // var_dump($data);die;
                }

            
        }
        
        $this->success('新增成功', 'admin/index/index');

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $goods = good::get($request->id);
        $goods->is_on_sale = $request->sale;
        $goods->save();

    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
